import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/db/database.dart';
import 'package:smart_translator/app/views/controller/rt_call_controller.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../utils/tips.dart';
import '../../../views/controller/DocTransViewController.dart';
import '../../../views/controller/IndexViewController.dart';
import '../../../views/controller/MineViewController.dart';
import '../../../views/controller/VeadioViewController.dart';
import '../../../views/views/doc_trans_view_view.dart';
import '../../../views/views/index_view_view.dart';
import '../../../views/views/mine_view_view.dart';
import '../../../views/views/transcript_view_view.dart';
import '../../../views/views/rt_call_view.dart';

class HomeController extends GetxController {

  var currentTabIndex = 0.obs;

  List<Widget> pages = [IndexViewView(),RtCallView(),
    TranscriptViewView(),MineViewView()];

  // 创建Scaffold的GlobalKey
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  var allSessionCount = 0.obs;
  var unclassifiedSessionCount = 0.obs;
  var rubbishSessionCount = 0.obs;

  RxList<Widget> folderList = RxList<Widget>();

  var hasAllChecked = true.obs;
  var hasUnclassify = false.obs;
  var hasRubbishRecycle = false.obs;

  var customerFolderItemCheckedId = AppConst.FOLDER_TYPE_UN_CLASSIFIED.obs;

  RxList<Map> customerFolderSource = RxList<Map>();

  //被选中的文件夹名称.
  var folderNameChecked = '全部文件'.obs;
  var folderIdChecked = AppConst.FOLDER_TYPE_UN_CLASSIFIED.obs; // 未分类.  100000未分类, -1 回收站.
  // session页面的数目.
  var sessionCount = 0.obs;


  var createTimeOrderType = false.obs; // 倒序.
  var updateTimeOrderType = false.obs; // 倒序.

  var createTimeOrderHasChecked = true.obs;
  var updateTimeOrderHasChecked = false.obs;

  RxList<Session> sessionList = RxList<Session>();


  void openDrawer() {
    initSessionCount();
    getAllFolders();
    // 通过key获取ScaffoldState并打开抽屉
    scaffoldKey.currentState?.openDrawer();
  }

  void closeDrawer() {
    // 关闭抽屉（当需要手动关闭时使用）
    Get.back();
  }

  @override
  void onInit() {
    super.onInit();
    Get.put(IndexViewController(),permanent: true);
    Get.put(VeadioViewController(),permanent: true);

    Get.put(DocTransViewController(),permanent: true);
    Get.put(MineViewController(),permanent: true);
    Get.put(RtCallController(),permanent: true);
  }

  void initSessionCount() async {
    allSessionCount.value = (await DbDAOHelper().obtainAllSession()).length;
    unclassifiedSessionCount.value = (await DbDAOHelper().obtainSessionByFolderId(AppConst.FOLDER_TYPE_UN_CLASSIFIED)).length;
    rubbishSessionCount.value = (await DbDAOHelper().obtainSessionByFolderId(AppConst.FOLDER_TYPE_RUBBISH)).length;
  }



  @override
  void onReady() {
    super.onReady();
    getALLSessionCollections();
  }

  @override
  void onClose() {
    super.onClose();
  }


  Widget getPageItem (int tabIndex) {
    return pages[tabIndex];
  }

  void onTap(int tabIndex) {
    currentTabIndex.value = tabIndex;

  }

  void addNewFolder() {
    CommonWidgets.showConfirmDialogWithTextFiled(Get.context!, DataCallBack(
        confirmCallBack: (v) {
          DbDAOHelper().addFolder(v);
          getAllFolders();

        },
        cancleCallBack: (v) {
        }
    ),'文件夹名称');
  }




  void getAllFolders() {
    folderList.clear();
    DbDAOHelper().obtainAllFolders().then((folders) {
      folders.forEach((item) async {
        int folderSize = (await DbDAOHelper().obtainSessionByFolderId(item.id)).length;
        folderList.add(
            InkWell(
              onTap: () {
                HomeController homeController = Get.find<HomeController>();
                homeController.customerFolderChecked(item);
              },
              child: Container(
                  padding: EdgeInsets.only(top: 14.h,bottom: 14.h,left: 13.h),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8), // Optional: add border radius
                    color: customerFolderItemCheckedId.value == item.id ? Colors.white : Colors.white.withValues(alpha: 0)
                  ),
                  child: Row(
                    children: [
                      Image.asset('assets/images/icon_sildeside_blue_folder.png',width: 16.w,height: 16.h,),
                      SizedBox(width: 5.w,),
                      Text('${item.f_name}(${folderSize})')
                    ],
                  ),
              ),
            )
        );
      });
    });

  }


  void allFolderChecked() {
    folderNameChecked.value = '全部文件';
    hasAllChecked.value = true;
    hasUnclassify.value = false;
    hasRubbishRecycle.value = false;

    customerFolderItemCheckedId.value = -2; //代表定制的文件夹全部不选中.
    sessionCount.value = allSessionCount.value;
    getAllFolders();
    // Get.back();
    getALLSessionCollections();
    folderIdChecked.value = AppConst.FOLDER_TYPE_UN_CLASSIFIED;
    Get.back();
  }

  void unClassifyFolderCheckced() {
    folderNameChecked.value = '未分类';
    hasAllChecked.value = false;
    hasUnclassify.value = true;
    hasRubbishRecycle.value = false;

    customerFolderItemCheckedId.value = -2; //代表定制的文件夹全部不选中.

    sessionCount.value = unclassifiedSessionCount.value;
    getAllFolders();
    // Get.back();
    getSessionCollectionsById(AppConst.FOLDER_TYPE_UN_CLASSIFIED);
    folderIdChecked.value = AppConst.FOLDER_TYPE_UN_CLASSIFIED;
    Get.back();
  }

  void rabishFolderChecked() {
    folderNameChecked.value = '回收站';
    hasAllChecked.value = false;
    hasUnclassify.value = false;
    hasRubbishRecycle.value = true;

    customerFolderItemCheckedId.value = -2; //代表定制的文件夹全部不选中.

    sessionCount.value = rubbishSessionCount.value;

    getAllFolders();
    // Get.back();
    getSessionCollectionsById(AppConst.FOLDER_TYPE_RUBBISH);
    folderIdChecked.value = AppConst.FOLDER_TYPE_RUBBISH;
    Get.back();
  }


  void customerFolderChecked(FolderData folder) {
    customerFolderItemCheckedId.value = folder.id;
    folderNameChecked.value = folder.f_name;
    hasAllChecked.value = false;
    hasUnclassify.value = false;
    hasRubbishRecycle.value = false;

    (DbDAOHelper().obtainSessionByFolderId(folder.id)).then((sessions){
      sessionCount.value = sessions.length;
    });

    getAllFolders();
    getSessionCollectionsById(folder.id);
    folderIdChecked.value = folder.id;
    Get.back();
  }


  void getALLSessionCollections() {
    DbDAOHelper().obtainAllSession().then((sessions) {
      sessionList.value = sessions;
      sessionCount.value = sessions.length;
    });
  }

  void getSessionCollectionsById (int folderId) {
    DbDAOHelper().obtainSessionByFolderId(folderId).then((sessions) {
      sessionList.value = sessions;
      sessionCount.value = sessions.length;
    });
  }



  // 详情页关闭之后选择刷新.
  void refreshAudioFiles() {
    if (folderIdChecked.value == AppConst.FOLDER_TYPE_UN_CLASSIFIED) {
      getALLSessionCollections();
    } else {
      getSessionCollectionsById(folderIdChecked.value);
    }


  }

  void createSession(DataCallBack callBack) {
    DbDAOHelper().saveSession(folderIdChecked.value, 'pending', 0).then((keyId) {
      callBack.businessCallBack!(keyId);
    });
  }


  void searchCustomerFolder(v) {
      if (v.toString().trim() == '') {
        getAllFolders();
      } else {
        getFoldersByFolderName(v);

      }
  }

  void getFoldersByFolderName(String folderName) {
    folderList.clear();
    DbDAOHelper().obtainAllFolders().then((folders) {
      folders.forEach((item) async {
        if (item.f_name.contains(folderName)) {
          int folderSize = (await DbDAOHelper().obtainSessionByFolderId(item.id)).length;
          folderList.add(
              InkWell(
                onTap: () {
                  HomeController homeController = Get.find<HomeController>();
                  homeController.customerFolderChecked(item);
                },
                child: Container(
                  padding: EdgeInsets.only(top: 14.h,bottom: 14.h,left: 13.h),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8), // Optional: add border radius
                      color: customerFolderItemCheckedId.value == item.id ? Colors.white : Colors.white.withValues(alpha: 0)
                  ),
                  child: Row(
                    children: [
                      Image.asset('assets/images/icon_sildeside_blue_folder.png',width: 16.w,height: 16.h,),
                      SizedBox(width: 5.w,),
                      Text('${item.f_name}(${folderSize})')
                    ],
                  ),
                ),
              )
          );
        }

      });
    });

  }


  void clearRabbish() {
     if (sessionCount.value == 0 ) {
         Tips.showToast('回收站没有文件');
         return;
     }

     CommonWidgets.showConfirmDialog(Get.context!, '确认', '确定要清空回收站吗?', '确定', '取消', DataCallBack(
       confirmCallBack: (v) {
         print('确定...');

         //先搜索出来进行文件删除,再进行记录删除.
         DbDAOHelper().obtainSessionByFolderId(AppConst.FOLDER_TYPE_RUBBISH).then((sessions) {
           sessions.forEach((item) {
              String filePath =   item.audio_path;
              File file = File(filePath);
              file.exists().then((isExist) {
                   if(isExist) {
                       file.delete();
                   }
              });
           });
         });

         DbDAOHelper().deleteSessionByFolderId(AppConst.FOLDER_TYPE_RUBBISH).then((deleteCount) {
            Tips.showToast('文件已经清空.');
            getSessionCollectionsById(AppConst.FOLDER_TYPE_RUBBISH);
         });
       },
       cancleCallBack: (v) {
         print('取消...');
       }
     ));


  }

  void orderByCreateTime() {
    createTimeOrderHasChecked.value = true;
    updateTimeOrderHasChecked.value = false;
    if (!createTimeOrderType.value) { // 升序.
      createTimeOrderType.value = !createTimeOrderType.value;
      sessionList.sort((item1, item2) {
        return item1.create_time.isBefore(item2.create_time) ? 1 : -1;
      });
    } else { // 倒序.
      createTimeOrderType.value = !createTimeOrderType.value;
      sessionList.sort((item1, item2) {
        return item2.create_time.isBefore(item1.create_time) ? 1 : -1;
      });
    }

    Get.back();
  }


  void orderByUpdateTime() {
    createTimeOrderHasChecked.value = false;
    updateTimeOrderHasChecked.value = true;
    if (!updateTimeOrderType.value) { // 升序.
      updateTimeOrderType.value = !updateTimeOrderType.value;
      sessionList.sort((item1, item2) {
        return item1.update_time.isBefore(item2.update_time) ? 1 : -1;
      });
    } else {
      updateTimeOrderType.value = !updateTimeOrderType.value;
      sessionList.sort((item1, item2) {
        return item2.update_time.isBefore(item1.update_time) ? 1 : -1;
      });
    }

    Get.back();
  }

}
